package com.example.design.proxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Description CgLib代理类
 * @ClassName CglibProxy
 * @Author Yumuhui
 * @Date 2020/5/14 1:15
 * @Version 1.0.0
 */
public class CglibProxy implements MethodInterceptor {
    private Object target;
    public Object getInstance(final Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("before proxy");
        // 不可以使用invoke,会陷入死循环
//        Object result = methodProxy.invoke(object, args);
        Object result = methodProxy.invokeSuper(object, args);

        System.out.println("after proxy");
        return result;
    }
}
